<?php

namespace yan\backendclient\modules\backendmodule\controllers;

use Yii;
use yan\backendclient\modules\backendmodule\models\BackendModule;
use yan\backendclient\modules\backendmodule\models\BackendModuleSql;
use yan\backendclient\modules\backendmodule\models\Gii;
use yii\data\ArrayDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * DefaultController implements the CRUD actions for BackendModule model.
 */
class GiiController extends \yan\backendclient\controllers\DebugController
{
    

    /**
     * Lists all BackendModule models.
     * @return mixed
     */
    public function actionIndex($id)
    {
        $model  = $this->findModel($id);

        $formModel = new Gii();
        $formModel->module_id = $id;
        $formModel->type = Yii::$app->request->get('type', Gii::TYPE_MODEL);
            $list = [];
        if($formModel->type == Gii::TYPE_MODEL){
            $formModel->scenario = Gii::TYPE_MODEL;
            $sqls = BackendModuleSql::find()->where(['module_id'=>$id])->all();
            foreach ($sqls as $key => $value) {
                $tableName = $value->rawTableName;
                $list[$tableName] = $tableName;
            }
        }else if($formModel->type == Gii::TYPE_CURD){
            $formModel->scenario = Gii::TYPE_CURD;
            $list = $formModel->getClassModelList();
            $formModel->controller_id = !empty($formModel->controller_id) ? $formModel->controller_id : 'default';
        }
        $answers = Yii::$app->request->post('answers');

        $params = [];
        if($formModel->load(Yii::$app->request->post()) && $formModel->validate()){
            $files = $formModel->generate($formModel->type);
            $generator = $formModel->getGenerate();
            $generator->saveStickyAttributes();
            if ($generator !== null && !empty($answers)) {
                $params['hasError'] = !$generator->save($files, (array) $answers, $results);
                $params['results'] = $results;
            } else {
                $params['files'] = $files;
                $params['answers'] = $answers;
            }
        }

        return $this->render('index',['model'=>$formModel,'list'=>$list, 'params'=>$params]);
    }
    protected function findModel($id)
    {
        if (($model = BackendModule::find()->where(['module_id'=>$id])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
